package pos.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import pos.domain.*;

public class JDBCBarrioDAO implements IBarrioDAO{
	
	Connection conn = ConnectionManager.getInstance().checkOut();

	@Override
	public Barrio select(int idBarrio) {
		PreparedStatement stmt = null;
		ResultSet result = null;
		Barrio b = null;
		String sql = "SELECT * FROM barrio WHERE (idBarrio = ?) ";

		try {
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, idBarrio);
			result = stmt.executeQuery();

			result.next();
			b = new Barrio();
			b.setIdBarrio(result.getInt("idBarrio"));
			b.setNombre(result.getString("nombre"));
			b.setColindantes(getColindantes(b));

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
			}
		}
		return b;
	}
	
	private List<Barrio> getColindantes(Barrio barrio){
		PreparedStatement stmt = null;
		ResultSet result = null;
		Barrio b = null;
		String sql = "SELECT * FROM barriocolindante WHERE idBarrio = ?";
		List<Barrio> lista = new ArrayList<Barrio>();

		try {
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, barrio.getIdBarrio());
			result = stmt.executeQuery();

			while(result.next()){
				b = new Barrio();
				b.setIdBarrio(result.getInt("idBarrioColindante"));
				lista.add(b);
			}
				
		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (result != null) {
					result.close();
				}
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException e) {
			}
		}
		return lista;
	}

}
